<?php
/**
 * Created by PhpStorm.
 * User: hanbin
 * Date: 17/3/31
 * Time: 上午11:18
 */

namespace App\Logic\zhihu;

use App\Logic\BaseLogic;
use App\Server\zhihu\FeedbackModel;
use App\Server\zhihu\MemberModel;

/**
 * 用户相关
 * Class MemberLogic
 * @package App\Logic
 */
class MemberLogic extends BaseLogic
{
    /**
     * 注册
     * @param array $data
     * @return array
     */
    public static function register($data = [])
    {
        if ($data) {
            $mobile = $data['phone'];
            if (self::checkMobileIsRegister($mobile)) {
                return self::error('该手机号已经注册', 206);
            }
            $insert = [];
            $insert['phone'] = $mobile;
            $insert['userpwd'] = $data['userpwd'];
            $insert['api_version'] = API_VERSION;
            if (strrpos($_SERVER['HTTP_USER_AGENT'], 'Android')) {
                $registrationSource = MemberModel::$ANDROID;
            } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
                $registrationSource = MemberModel::$IOS;
            } else {
                $registrationSource = MemberModel::$WEB;
            }
            $insert['registration_source'] = $registrationSource;
            $insert['status'] = 1;
            $insert['update_time'] = time();
            $insert['create_time'] = time();
            $token = self::createToken($data['userpwd']);
            $insert['token'] = $token;
            $up = MemberModel::add($insert);
            if ($up) {
                $detail = MemberModel::where(['phone' => $mobile])->first();
                $result = [];
                $result['id'] = $detail['id'];
                $result['phone'] = $mobile;
                $result['token'] = $token;
                return self::success($result, 200, '注册成功');
            } else {
                return self::error('注册失败', 206);
            }
        } else {
            return self::error('请求参数有误', 206);
        }
    }

    /**
     * 判断手机是否已经存在
     * @param string $mobile
     * @return bool
     */
    private static function checkMobileIsRegister($mobile = '')
    {
        $detail = MemberModel::where(['phone' => $mobile])->orderBy('id', 'desc')->first();
        if ($detail) {
            return $detail;
        } else {
            return false;
        }
    }

    /**
     * 更新用户资料
     *
     * @param int $id
     * @param array $data
     * @return array
     */
    public static function updateInfo($id = 0, $data = [])
    {
        if ($id && $data) {
            $up = MemberModel::updateInfo(['id' => $id], $data);
            if ($up) {
                return self::success(['flag' => 1], 200, '更新成功');
            } else {
                return self::error('更新失败', 206);
            }
        } else {
            return self::error('请求参数有误', 206);
        }
    }

    /**
     * 登录
     * @param array $data
     * @return array
     */
    public static function login($data = [])
    {
        if ($data) {
            $userDetail = MemberModel::first(['phone' => $data['phone']]);
            if (!$userDetail) {
                return self::error('该用户不存在', 206);
            }
            if ($userDetail['userpwd'] != $data['userpwd']) {
                return self::error('密码不正确', 206);
            }
            $token = self::createToken($data['userpwd']);
            $up = MemberModel::updateInfo(['phone' => $userDetail['phone']], ['token' => $token, 'update_time' => time()]);
            if ($up) {
                $result = $userDetail;
                $result['token'] = $token;
                unset($result['userpwd']);
                unset($result['update_time']);
                unset($result['create_time']);
                unset($result['api_version']);
                unset($result['registration_source']);
                return self::success($result, 200, '登录成功');
            } else {
                return self::error('登录失败', 206);
            }

        } else {
            return self::error('请求参数有误', 206);
        }
    }

    /**
     * 忘记密码
     *
     * @param array $data
     * @return array
     */
    public static function forget($data = [])
    {
        if ($data) {
            $userDetail = MemberModel::first(['phone' => $data['phone']]);
            if (!$userDetail) {
                return self::error('该用户不存在', 206);
            }
            $token = self::createToken($data['userpwd']);
            $up = MemberModel::updateInfo(['id' => $userDetail['id']], ['token' => $token, 'userpwd' => $data['userpwd'], 'update_time' => time()]);
            if ($up) {
                $result = $userDetail;
                $result['token'] = $token;
                unset($result['userpwd']);
                unset($result['update_time']);
                unset($result['create_time']);
                unset($result['api_version']);
                unset($result['registration_source']);
                return self::success($result, 200, '重置密码成功');
            } else {
                return self::error('重置密码失败', 206);
            }

        } else {
            return self::error('请求参数有误', 206);
        }
    }


    /**
     * 生成Token
     * @param string $password
     * @return array|string
     */
    private static function createToken($password = '')
    {
        if (!$password) {
            return self::error('密码不能为空', 206);
        } else {
            $token_key = md5(getClient_id() . $password . time() . mt_rand(9, 99999));
            $token = sha1($token_key . mt_rand(9, 99999) . time());
            return $token;
        }
    }


    /**
     * 获取用户资料
     * @param $userId
     * @return array
     */
    public static function userInfo($userId)
    {
        if (!$userId) {
            return self::error('请登录', 208);
        }
        $userDetail = MemberModel::first(['id' => $userId]);
        if ($userDetail) {
            unset($userDetail['password']);
            unset($userDetail['update_time']);
            unset($userDetail['create_time']);
            unset($userDetail['api_version']);
            unset($userDetail['registration_source']);
            return self::success($userDetail, 200, '登录成功');
        } else {
            return self::error('该用户不存在', 208);
        }
    }


}